<script setup lang="ts" name="VaccineLibrary">
import {ColorTheme, ColorRed} from '@/api/config'
import dDialog from '@/components/dDialog/dDialog.vue'
import {defaultLayout, defaultPage, defaultPageSize, defaultPageSizes, PageConfig} from '@/components/dTable/dFooter'
import {OperButton, SearchFromItem, SearchButton} from '@/components/dTable/dHeader'
import {HeaderData, RowOperbuttons, Operation as Oper} from '@/components/dTable/dTable'
import operation from '@/components/dTable/components/operation.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import AddVaccineLibrary from './addVaccineLibrary.vue'
import {ElMessage, FormRules} from 'element-plus'
import {onBeforeMount, reactive, ref} from 'vue'
import {showMessageBox} from '@/util/element'
import {deleteVaccineStore, getVaccineStore, VaccineStoreList} from '@/api/medicalExaminerDesk/beginPhysicalExamination/vaccinationHistory'
import { NoChinese, NotLeadingAndTrailingSpaces } from '@/util/common'
defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  }
})

// 新增或者编辑弹窗
const showAddVaccineDialog = ref(false)

// 新增或者编辑弹窗类型
const dialogType = ref('')

// 空数据
const emptyData = {inocCode: '', inocName: '', pinyinCode: '', unitsName: ''}

// 疫苗库数据
const vaccineData = ref<VaccineStoreList>({...emptyData})

const emits = defineEmits(['close'])

//显示加载状态
const showLoading = ref(false)

//表头
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  }
])

//搜索项
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '疫苗代码',
    placeholder: '请输入疫苗代码',
    type: 'input',
    prop: 'inocCode',
    enterSubmit: true
  },
  {
    label: '疫苗名称',
    placeholder: '请输入疫苗名称',
    type: 'input',
    prop: 'inocName',
    enterSubmit: true
  }
])
// 表格搜索
const searchFromData = reactive({})
// 表格搜索校验
const searchFromRules = reactive<FormRules>({
  inocCode: [
    {
      message: '最多50位字母、数字、字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入字母、数字、字符',
      pattern: NoChinese,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  inocName: [
    {
      message: '最多100个字符',
      trigger: ['change', 'blur'],
      max: 100
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ]
})

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'inocCode',
    label: '疫苗代码',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'inocName',
    label: '疫苗名称',
    columnType: 'text',
    align: 'left',
    'min-width': '200'
  },
  {
    prop: 'unitsName',
    label: '接种机构',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '80',
    fixed: 'right'
  }
])

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([{type: 'search'}, {type: 'clear'}])

//数据
const tableData = ref<Array<VaccineStoreList & RowOperbuttons>>([])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

// 行操作按钮
const rowOperButtons: Array<Oper> = [
  {
    code: 'edit',
    label: '编辑',
    iconConfig: {
      icon: 'common-edit',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  },
  {
    code: 'delete',
    label: '删除',
    iconConfig: {
      icon: 'common-delete',
      type: 'custom',
      color: ColorRed,
      size: 20
    }
  }
]

//后端数据拼接字段
const setTableData = (data: Array<VaccineStoreList>) => {
  const dataArr: Array<VaccineStoreList & RowOperbuttons> = []
  data.forEach((item) => {
    dataArr.push({...item, oper: rowOperButtons})
  })
  tableData.value = dataArr
}

//搜索数据
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  getVaccineStore({
    ...searchFromData,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  })
    .then((res) => {
      const {records} = res.data.data
      pageConfig.value.total = res.data.data.total === null ? 0 : res.data.data.total
      setTableData(records)
    })
    .catch((error) => {
      console.warn(error)
    })
    .finally(() => {
      showLoading.value = false
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

//操作按钮事件
const onOperation = (code: string) => {
  if (code === 'add') {
    vaccineData.value = {...emptyData} // 清空数据
    dialogType.value = 'add'
    showAddVaccineDialog.value = true
  }
}

//操作插槽事件
const cellOperation = (code: string, row: VaccineStoreList) => {
  if (code === 'edit') {
    vaccineData.value = {
      id: row.id,
      inocCode: row.inocCode, // 疫苗代码
      inocName: row.inocName, // 疫苗名称
      pinyinCode: row.pinyinCode, // 拼音码
      unitsName: row.unitsName // 接种机构
    }
    dialogType.value = 'edit'
    showAddVaccineDialog.value = true
  } else if (code === 'delete') {
    showMessageBox('是否确认删除此疫苗？', {title: '删除确认', mesageType: 'base'})
      .then(() => {
        row.id &&
          deleteVaccineStore(row.id).then(() => {
            ElMessage.success('删除成功！')
            searchData()
          })
      })
      .catch((error) => {
        console.warn(error)
      })
  }
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

/**
 * @description: 关闭新增保存弹窗
 * @return {*}
 */
const onCloseVaccineDialog = () => {
  showAddVaccineDialog.value = false
  searchData()
}

/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onCancel = () => {
  emits('close')
}
/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onClose = () => {
  emits('close')
}

onBeforeMount(() => {
  searchData()
})
</script>
<template>
  <d-dialog
    title="疫苗库维护"
    :show-dialog="showDialog"
    :hide-save-btn="true"
    cancel-text="关闭"
    :width="1100"
    @cancel="onCancel"
    @close="onClose"
  >
    <d-table-promote
      :oper-buttons="operButtons"
      :search-form-items="searchFromItems"
      :search-buttons="searchButtons"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      search-from-justify="flexStart"
      class="vaccine-library-table"
      :show-loading="showLoading"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
      </template>
    </d-table-promote>
  </d-dialog>
  <add-vaccine-library v-if="showAddVaccineDialog" :vaccine-data="vaccineData" :show-dialog="showAddVaccineDialog" :dialog-type="dialogType" @close="onCloseVaccineDialog" />
</template>
<style scoped lang="less">
.vaccine-library-table {
  height: 600px;
}
</style>
